package cn.com.dhcc.turbo.web.controller.monitor;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.XstreamUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.api.RouteLog;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpFileData;
import cn.com.dhcc.turbo.service.exch.filedata.CrossNetTmpFileDataService;

@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu=LEAF_MENU.GAP_FILE_MONITOR_EXTRANET)
public class ExtranetFileDataController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	private CrossNetTmpFileDataService fileDataService;

	@RequestMapping(value = "/extranet_file_data_list")
	public String list(
			Model model, 
			Pager pager, 
			String sendNodecode, 
			String sendSyscode, 
			String recvNodecode, 
			String recvSyscode, 
			String sendStatus,
			String startCreated, 
			String endCreated, 
			String orderName, 
			String order) {
		try {
			WhereCondition searchData = new WhereCondition();
			searchData.where().eq("1", "1");
			if (StrUtil.isNotBlank(sendNodecode)) {
				searchData.and().like("send_nodecode", sendNodecode);
			}
			if (StrUtil.isNotBlank(sendSyscode)) {
				searchData.and().like("send_adaptorcode", sendSyscode);
			}
			if (StrUtil.isNotBlank(recvNodecode)) {
				searchData.and().like("recv_nodecode", recvNodecode);
			}
			if (StrUtil.isNotBlank(recvSyscode)) {
				searchData.and().like("recv_adaptorcode", recvSyscode);
			}
			//这里对发生中的状态进行了处理，把本地发送和远程发送都看做为发送中
			if (StrUtil.isNotBlank(sendStatus)) {
				if (AppConst.SendStatus.LOCAL_SENDING.value().equals(sendStatus)) {
					searchData.and().leftBracket()
								.eq("send_status", sendStatus)
								.or()
								.eq("send_status", AppConst.SendStatus.REMOTE_SENDING.value())
								.rightBracket();
				} else {
					searchData.and().eq("send_status", sendStatus);
				}
			}
			//时间范围从那天到那天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
				searchData.and().between("created", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
			}

			//时间范围，大于等于某天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {	
				searchData.and().between("created", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
			}

			//时间范围，小于等于某天
			if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {	
				searchData.and().between("created", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
			}
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("created  desc");
			}
			PagerData<CrossNetTmpFileData> datas = fileDataService.getPagerList(pager, searchData);
            model.addAttribute(DATA_KEY, datas.getDatas());
            
    		model.addAttribute("send_node_list", fileDataService.getSendNodeList());//获取CM_DATA类型发送节点列表
			model.addAttribute("recv_node_list", fileDataService.getRecvNodeList());//获取CM_DATA类型的接收节点列表
            
            model.addAttribute("send_status_list", AppConst.SendStatus.values());
            setTotoal(model, datas.getTotal());
			return "monitor/extranet_file_data_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 查看页面
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/extranet_file_data_get")
	public String get(Model model, String id) {
		try {
			CrossNetTmpFileData vo = fileDataService.get(id);
			//获取本节点的网络类型网络类型（0：外网）（1：内网）
			//EXTRA("2", "水利政务外网"), INNER("1", "水利政务内网");
			String routeLogXml = vo.getRoutelog();
			RouteLog routeLog =XstreamUtil.toObject(RouteLog.class,routeLogXml);
			model.addAttribute(DATA_KEY, vo);
			model.addAttribute("routeLog", routeLog);
			
			model.addAttribute("netType", NodeInfoParam.NODE_NET_TYPE);
			return "monitor/extranet_file_data_get";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 根据ID删除记录
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/extranet_file_data_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(Model model, String id) {
		try {
			fileDataService.delete(id);
			return jsonSuccessResult("删除成功");
		} catch (Exception e) {
			logger.error("删除失败", e);
			return jsonFailResult("删除失败");
		}
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/extranet_file_data_deletes", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteByIds(@RequestParam("ids") String ids) {
		String msg = "";
		try {
			msg = "删除成功";
			fileDataService.deleteBatchById(ids.split(","));
			return jsonSuccessResult(msg);
		} catch (Exception e) {
			msg = "批量删除失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
}
